package com.beici.waterghost.filter;

import com.alibaba.fastjson.JSONObject;
import com.beici.waterghost.model.resultes;
import com.beici.waterghost.model.user;
import com.beici.waterghost.service.impl.userServiceImpl;
import com.beici.waterghost.utils.takeUtils;
import org.apache.tomcat.util.http.parser.Authorization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @auther WaterGhost
 * @date 2022/1/26 18:08
 */
@Component
public class TOKENVerifityFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private userServiceImpl userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        // 解析出TOKEN
        String authorization = request.getHeader("Authorization");
        try {
            String TOKEN  = authorization.split(" ")[1];
            // 如果存在那么解析出他的主体用户
            user user = getUser(TOKEN);
            if (user==null){
                String jsonString = JSONObject.toJSONString(resultes.NoAuthenction());
                PrintWriter writer = response.getWriter();
                writer.println(jsonString);
                writer.close();
            }else {
                SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user,null, null));
                filterChain.doFilter(request,response);
            }

        }catch (NullPointerException e){
            // 直接放行做下一步路径拦截判断过滤器
            filterChain.doFilter(request,response);
        }

    }

    private user getUser(String TOKEN){
        // 解析TOKEN
        String userId = redisTemplate.opsForValue().get(TOKEN);
        if (takeUtils.StringIsNullOrEmpty(userId)){
            resultes resultes = userService.selectUserDetailInfo(Long.valueOf(userId));
            if (resultes.getData() instanceof user && resultes.getData()!=null){
                return (user) resultes.getData();
            }

        }
        return null;
    }
}
